/**
 * Software License, Version 1.0
 * 
 * Copyright 2003 The Trustees of Indiana University.  All rights reserved.
 * 
 *
 *Redistribution and use in source and binary forms, with or without 
 *modification, are permitted provided that the following conditions are met:
 *
 *1) All redistributions of source code must retain the above copyright notice,
 * the list of authors in the original source code, this list of conditions and
 * the disclaimer listed in this license;
 *2) All redistributions in binary form must reproduce the above copyright 
 * notice, this list of conditions and the disclaimer listed in this license in
 * the documentation and/or other materials provided with the distribution;
 *3) Any documentation included with all redistributions must include the 
 * following acknowledgement:
 *
 *"This product includes software developed by the Community Grids Lab. For 
 * further information contact the Community Grids Lab at 
 * http://communitygrids.iu.edu/."
 *
 * Alternatively, this acknowledgement may appear in the software itself, and 
 * wherever such third-party acknowledgments normally appear.
 * 
 *4) The name Indiana University or Community Grids Lab or NaradaBrokering, 
 * shall not be used to endorse or promote products derived from this software 
 * without prior written permission from Indiana University.  For written 
 * permission, please contact the Advanced Research and Technology Institute 
 * ("ARTI") at 351 West 10th Street, Indianapolis, Indiana 46202.
 *5) Products derived from this software may not be called NaradaBrokering, 
 * nor may Indiana University or Community Grids Lab or NaradaBrokering appear
 * in their name, without prior written permission of ARTI.
 * 
 *
 * Indiana University provides no reassurances that the source code provided 
 * does not infringe the patent or any other intellectual property rights of 
 * any other entity.  Indiana University disclaims any liability to any 
 * recipient for claims brought by any other entity based on infringement of 
 * intellectual property rights or otherwise.  
 *
 *LICENSEE UNDERSTANDS THAT SOFTWARE IS PROVIDED "AS IS" FOR WHICH NO 
 *WARRANTIES AS TO CAPABILITIES OR ACCURACY ARE MADE. INDIANA UNIVERSITY GIVES
 *NO WARRANTIES AND MAKES NO REPRESENTATION THAT SOFTWARE IS FREE OF 
 *INFRINGEMENT OF THIRD PARTY PATENT, COPYRIGHT, OR OTHER PROPRIETARY RIGHTS. 
 *INDIANA UNIVERSITY MAKES NO WARRANTIES THAT SOFTWARE IS FREE FROM "BUGS", 
 *"VIRUSES", "TROJAN HORSES", "TRAP DOORS", "WORMS", OR OTHER HARMFUL CODE.  
 *LICENSEE ASSUMES THE ENTIRE RISK AS TO THE PERFORMANCE OF SOFTWARE AND/OR 
 *ASSOCIATED MATERIALS, AND TO THE PERFORMANCE AND VALIDITY OF INFORMATION 
 *GENERATED USING SOFTWARE.
 */
package cgl.narada.wsinfra.wsrm.storage.impl;


import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

import cgl.narada.util.ConfigurationParamsReader;
import cgl.narada.wsinfra.wsrm.storage.WsrmAuditStorageOperations;
import cgl.narada.wsinfra.wsrm.storage.WsrmPolicyStorageOperations;
import cgl.narada.wsinfra.wsrm.storage.WsrmProtocolStorageOperations;
import cgl.narada.wsinfra.wsrm.storage.WsrmSequenceInfoStorageOperations;
import cgl.narada.wsinfra.wsrm.storage.WsrmStorageException;
import cgl.narada.wsinfra.wsrm.storage.WsrmStorageService;

/**
 * <p>Title: WsrmStorageServiceImpl </p>
 * <p>Description: The WsrmStorageService provides accesses to 3 interfaces
 *  which cover the gamut of storage operations specific to the WSRM
 * protocol.</p>
 * @author Beytullah Yildiz
 */

public class WsrmStorageServiceImpl
    extends WsrmStorageService {

  private Connection connection;

  private String moduleName = "WsrmStorageServiceImpl: ";
  private String jdbcDriver = "org.gjt.mm.mysql.Driver";
  private String connectionInfo =
      "jdbc:mysql://everest.ucs.indiana.edu:3306/wsrm";
  private String connectionProvider = "jdbc:mysql";
  private String connectionHost = "everest.ucs.indiana.edu";
  private String connectionPort = "3306";
  private String connectionDatabase = "wsrm";
  private String dbUserName = "";
  private String dbUserPassword = "";

  private static Properties serviceDefaults;
  private String propertiesFileName = "";

  public WsrmStorageServiceImpl(String propertiesFileName) throws
      WsrmStorageException {
    this.propertiesFileName = propertiesFileName;
    createNewConnection(propertiesFileName);

  }

  /** creates database connection */
  public void createNewConnection(String fileName) throws WsrmStorageException {

    if (connection == null) {
      loadProperties(fileName);
      initialize();
    }
  }

  /** gets the connection object to the database */
  public Connection getConnection() throws WsrmStorageException {
    if (connection == null) {
      throw new WsrmStorageException(moduleName +
                                     "Connection is null");
    }
    return connection;
  }

  /** This method is used to initialize the storage interfaces and tables
     when the service starts up for the first time or after a scheduled
     downtime or is recovering from an unforeseen failure. This method
     checks for consistencies across the storage and proceeds to initialize
     the ProtocolStorageOperations, SequenceInfoOperations and
     AuditStorageOperations.  This method throws an exception if there are
     storage related problems. */

  public void initialize() throws WsrmStorageException {

    loadJDBCDriver();
    boolean specifiedUserAndPassword = false;

    if (dbUserName != null && dbUserPassword != null) {
      if (dbUserName != "" && dbUserPassword != "") {
        specifiedUserAndPassword = true;
      }
    }
    System.out.println("connection info " + connectionInfo);

    try {

      if (specifiedUserAndPassword) {
        System.out.println(moduleName + "Trying to create a connection " +
                           "UserId =" + dbUserName + " Password =" +
                           dbUserPassword);

        connection = DriverManager.getConnection(connectionInfo,
                                                 dbUserName, dbUserPassword);
      }
      else {
        System.out.println(moduleName +
                           "UserId/Password for Database not specified");
        connection = DriverManager.getConnection(connectionInfo);
      }

      System.out.println(moduleName + "Database connection is succesful");
    }
    catch (SQLException ex) {
      ex.printStackTrace();
      throw new WsrmStorageException(moduleName +
                                     "JDBC connection could not be initiated");
    }

  }

  /** loads database driver */
  private void loadJDBCDriver() throws WsrmStorageException {

    try {

      Class.forName(jdbcDriver).newInstance();
      System.out.println("driver is loaded succesfully");
    }
    catch (InstantiationException ex) {
      throw new WsrmStorageException(moduleName +
                                     "JDBC driver instantiation exception");
    }
    catch (IllegalAccessException ex) {
      throw new WsrmStorageException(moduleName +
                                     "JDBC driver illegal access exception");
    }
    catch (ClassNotFoundException ex) {
      throw new WsrmStorageException(moduleName + "JDBC driver class not found");
    }
  }

  /** gets Properties object by given file location. If file could not
     be found it throws exception*/
  public Properties getProperties(String fileLocation) throws
      WsrmStorageException {

    File file = new File(fileLocation);
    Properties serviceProperties;

    if (!file.exists()) {
      throw new WsrmStorageException(moduleName
                                     + "Configuration file could not be read");
    }

    ConfigurationParamsReader configReader =
        new ConfigurationParamsReader(fileLocation);
    serviceProperties = configReader.getProperties(serviceDefaults);

    return serviceProperties;

  }

  /** loads parameters to connect database from properties file */

  public void loadProperties(String fileName) throws WsrmStorageException {

    System.out.println("FileName " + fileName);
    Properties properties = getProperties(fileName);

    String dbDriver = properties.getProperty(
        "Database_JDBC_Driver").trim();
    String dbConnectionProvider = properties.getProperty(
        "Database_ConnectionProvider", "").trim();
    String dbHost = properties.getProperty(
        "Database_ConnectionHost", "").trim();
    String dbPort = properties.getProperty(
        "Database_ConnectionPort", "").trim();
    String dbName = properties.getProperty(
        "Database_WSRM_Database", "").trim();
    String userName = properties.getProperty(
        "Database_WSRM_username", "").trim();
    String userPassword = properties.getProperty(
        "Database_WSRM_password", "").trim();

    setDbDriver(dbDriver);
    if (dbPort.equals("")) {
      setConnnectionInfo(dbConnectionProvider, dbHost,
                         dbName);
    }
    else {
      setConnnectionInfo(dbConnectionProvider, dbHost,
                         dbPort, dbName);
    }
    setUserParameters(userName, userPassword);

  }

  /** sets jdbc driver */
  public void setDbDriver(String dbDriver) {
    jdbcDriver = dbDriver;
  }

  /** sets connection parameters */
  public void setConnectionParameters(String provider, String host, String db) {
    connectionProvider = provider;
    connectionHost = host;
    connectionPort = "";
    connectionDatabase = db;
  }

  /** sets connection parameters */
  public void setConnectionParameters(String provider, String host, String port,
                                      String db) {
    connectionProvider = provider;
    connectionHost = host;
    connectionPort = port;
    connectionDatabase = db;

  }

  /** sets connection info without setting parameters */
  public void setConnnectionInfo(String connectInfo) {
    connectionInfo = connectInfo;
  }

  /** compose connection information from provided parameters  */
  public void setConnnectionInfo(String provider, String host, String db) {

    connectionInfo = provider + "://" + host + "/" + db;
    setConnectionParameters(provider, host, db);

  }

  /** compose connection information from provided parameter */
  public void setConnnectionInfo(String provider, String host, String port,
                                 String db) {

    connectionInfo = provider + "://" + host + ":" + port + "/" + db;
    setConnectionParameters(provider, host, port, db);
  }

  /** returns connection information */
  public String getConnectionInfo() {
    return connectionInfo;
  }

  /** sets user name and passwords */
  public void setUserParameters(String uname, String password) {
    dbUserName = uname;
    dbUserPassword = password;

  }

  /** Retrieves the reference to the WsrmProtocolStorageOperations by using
      given properties file. This method throws an exception if there were
      problems during the initialization of the StorageService due to
      inconsistencies or other storage related problems. */

  public WsrmProtocolStorageOperations getWsrmProtocolStorageOperations() throws
      WsrmStorageException {

    WsrmProtocolStorageOperationsImpl protocolStorageOperations =
        new WsrmProtocolStorageOperationsImpl(getConnection());
    return protocolStorageOperations;
  }

  /** Retrieves the reference to  WsrmSequenceInfoStorageOperations by using
      given properties file.This method throws an exception if there were
      problems during the initialization of the StorageService due to
      inconsistencies or other storage related problems. */
  public WsrmSequenceInfoStorageOperations
      getWsrmSequenceInfoStorageOperations() throws WsrmStorageException {

    WsrmSequenceInfoStorageOperationsImpl sequenceInfoStorageOperations =
        new WsrmSequenceInfoStorageOperationsImpl(getConnection());
    return sequenceInfoStorageOperations;

  }

  /** Retrieves the reference to  WsrmAuditStorageOperations by using given
     properties file. This method throws an exception if there were problems
     during the initialization of the StorageService due to inconsistencies
     or other storage related problems. */

  public WsrmAuditStorageOperations getWsrmAuditStorageOperations() throws
      WsrmStorageException {

    WsrmAuditStorageOperationsImpl auditStorageOperations =
        new WsrmAuditStorageOperationsImpl(getConnection());
    return auditStorageOperations;
  }

  public WsrmPolicyStorageOperations
      getWsrmPolicyStorageOperations() throws WsrmStorageException {

    WsrmPolicyStorageOperationsImpl wsrmPolicyStorageOperations =
       new WsrmPolicyStorageOperationsImpl(getConnection());
   return wsrmPolicyStorageOperations;

  }

  public static void main(String[] args) {
    String configurationFilename = "";
    WsrmStorageServiceImpl wsrmStorageServiceImpl1 = null;
    try {
      wsrmStorageServiceImpl1 =
          new WsrmStorageServiceImpl(configurationFilename);
      wsrmStorageServiceImpl1.getConnection();
    }
    catch (WsrmStorageException ex) {
      ex.printStackTrace();
    }

  }

}
